package cn.com.fone.modules.api.app.service.impl;


import cn.com.fone.modules.api.app.dao.UserDao;
import cn.com.fone.modules.api.app.entity.UserEntity;
import cn.com.fone.modules.api.app.form.LoginForm;
import cn.com.fone.modules.api.app.service.UserService;
import cn.com.fone.modules.api.common.exception.RRException;
import cn.com.fone.modules.api.common.split.annotation.SplitTable;
import cn.com.fone.modules.api.common.split.enums.SplitTableEnum;
import cn.com.fone.modules.api.common.validator.Assert;
import cn.com.fone.util.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    @SplitTable(value = "tb_user", strategy = SplitTableEnum.YYYY)
    public boolean insert(UserEntity userEntity) {
        return retBool(this.baseMapper.insert(userEntity));
    }

    @Override
    public UserEntity queryByMobile(String mobile) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(mobile);
        userEntity.setCreateTime(DateUtil.getDate("2017-01-01 05:55:30"));
        return baseMapper.selectOne(userEntity);
    }

    @Override
    public Integer updateUserById(UserEntity userEntity) {
        return baseMapper.update(userEntity, new EntityWrapper<UserEntity>().eq("user_id", "0"));
    }

    @Override
    public long login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        // 密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }

        return user.getUserId();
    }
}
